var row_back='';
var empty=false;
var i=4;

$(function () {
  $("select").dropkick();
});

$(document).ready(function(){

   $('#confirm').click(function(){
      if($('table').attr('type')==='update'){
         update_tbl();
      }else{
         add_tbl();
      }
   });

   $('.add').click(function(){

      i+=1;

      var new_list=[
      '<select value="Text" class="span3" name="list_'+i+'">',
         '<option value="integer">Integer</option>',
         '<option value="real">Real</option>',
         '<option value="text">Text</option>',
         '<option value="blob">Blob</option>',
      '</select>'
      ].join('');

      var new_toggle=[
      '<div class="toggle toggle-icon overtogle">',
         '<label class="toggle-radio fui-checkmark-16" for="toggleOption'+(i*2)+'A"></label>',
         '<input type="radio" id="toggleOption'+(i*2)+'A"/>',
         '<label class="toggle-radio fui-cross-16" for="toggleOption'+(i*2)+'A"></label>',
         '<input type="radio" id="toggleOption'+(i*2)+'B"/>',
      '</div>'
      ].join('');

      var row=$($(this).parent()).parent();

      if(empty){
         row=row_back.clone(true);
      }

      var cloned=row.clone(true);

      cloned.find('input[type=text]').attr('value','');
      cloned.find('.dk_container').detach();
      cloned.find('.col_type select').detach();
      cloned.find('.col_type').append(new_list);
      cloned.find('.toggle').detach();
      cloned.find('.col_null').append(new_toggle);

      toggleHandler(cloned.find('.toggle'));

      if(empty){
         $('tbody .last').before(cloned);
         empty=false;
         $('tbody').find('.msg_row').detach();
      }

      row.after(cloned);

      $("select").dropkick();
   });

   $('.remove').click(function(){
      var row=$($(this).parent()).parent();
      row_back=row.clone(true);
      row_back.addClass('resc');
      row.detach();

      if($('tbody').children().length===1){
         empty=true;
         var msg_row=row_back.clone(true);
         msg_row.addClass('msg_row list');
         msg_row.find(':nth-child(2), :nth-child(3), :nth-child(4)').detach();
         msg_row.find(':first').attr('colspan',4);
         msg_row.find(':first').html('<strong>You will create a table without columns</strong>');

         $('tbody .last').before(msg_row);
      }
   });

   $('#cancel').click(function(){
      $.jqDialog.confirm("Are you sure want to cancel the action? All progress will be lost",
         function() {
            if($('#cancel').hasClass('edit')){
               window.location.href='update';
            }else{
               window.location.href='home';
            }
         },      // callback function for 'YES' button
         function() { return false; }     // callback function for 'NO' button
      );
   });

   $('#tablename, .col_name input, .col_size input').keydown(function(){
      $(this).css('color','#34495e');
   });
});

var update_tbl=function(){

   var full_query=[];

   var database=$('.tile select').val();
   var tablename=$('#tablename').val();
   var old_tablename=$('#tablename').attr('old-val');

   if(tablename===''){
      $.jqDialog.alert("Please, give a name to your table", function() {
         $('#tablename').focus();
      });
      return false;
   }else if(tablename!=old_tablename){
      query='ALTER TABLE '+old_tablename+' RENAME TO '+tablename;
      alert(query);
   }

   $('.column').each(function(){
      if(!$(this).hasClass('last')){

         var col_name=$(this).find('.col_name input').val();
         var old_colname=$(this).find('.col_name input').attr('old-val');

         if(col_name!=''){
            if(col_name!=old_colname){
               alert('cambio el nombre de la columna '+old_colname+' a:'+col_name);
               query2='ALTER TABLE '+old_tablename;
            }


            var  col_type=$(this).find('.col_type select').val();
            var old_coltype=$(this).find('.col_type select').attr('old-val');

            if(col_type!=old_coltype){
               alert('cambio el tipo de:'+old_coltype+' a:'+col_type);
            }

            var col_size=$(this).find('.col_size input').val();
            var old_colsize=$(this).find('.col_size input').attr('old-val');

            if(col_size!=old_colsize){
               alert('cambio el tamaño de:'+old_colsize+' a:'+col_size);
            }

            var is_null=$(this).find('.col_null div').hasClass('toggle-off')?'NOT NULL':'';
            old_colnull=$(this).find('.col_null div').attr('old-val')==1?'NOT NULL':'';

            if(is_null!=old_colnull){
               alert('cambio de '+old_colnull+' a:'+is_null);
            }


            /*

            var column_query=col_name+' '+col_type+' '+col_size+' '+is_null+',';
            query.push(column_query);
            */
         }
      }
   });

   /*

   $('.column').each(function(){
      if(!$(this).hasClass('last')){
         var col_name=$(this).find('.col_name input').val();

         if(col_name!=''){
            var  col_type=$(this).find('.col_type select').val();
            var col_size=$(this).find('.col_size input').val();
            col_size=col_size!=''?'('+col_size+')':'';
            var is_null=$(this).find('.col_null div').hasClass('toggle-off')?'NOT NULL':'';
            var column_query=col_name+' '+col_type+' '+col_size+' '+is_null+',';
            query.push(column_query);
         }
      }
   });

   query[query.length-1]=query[query.length-1].split(',')[0];
   query.push(')');

   //alert(query.join(''));

   $('#query').attr('value',query.join(''));
   $('#database').attr('value',database);
   $('#form').submit();
   */

}

var add_tbl=function(){

   var database=$('.tile select').val();
   var tablename=$('#tablename').val();

   var namePattern=/^[a-z_][a-z0-9_]{2,20}$/
   var sizePattern=/^[0-9]{0,3}$/

   if(tablename===''){
      $.jqDialog.alert("Please, give a name to your new table", function() {
         $('#tablename').focus();
      });
      return false;
   }

   if(!namePattern.test(tablename)){
      $.jqDialog.alert("Please, give a correct name to your new table. The name will start with a letter or underscore, and only may contain alphanumeric characters and underscores", function() {
         $('#tablename').css('color','red');
         $('#tablename').focus();
      });
      return false;
   }

   var query=['CREATE TABLE '+tablename+' ('];

   var error=false;

   $('.column').each(function(){

      if(!$(this).hasClass('last')){

         var col_name=$(this).find('.col_name input');

         if(col_name.val()!=''){

            if(namePattern.test(col_name.val())){

               var  col_type=$(this).find('.col_type select').val();
               var col_size=$(this).find('.col_size input');

               if(!sizePattern.test(col_size.val())){
                  $.jqDialog.alert("Please, give a correct size to your new column or leave it in blank. The size will be an integer number", function() {
                     col_size.css('color','red').focus();
                  });
                  error=true;
                  return false;
               }

               col_size=col_size.val()!=''?'('+col_size.val()+')':'';

               var is_null=$(this).find('.col_null div').hasClass('toggle-off')?'NOT NULL':'';
               var column_query=col_name.val()+' '+col_type+' '+col_size+' '+is_null+',';
               query.push(column_query);

            }else{
               $.jqDialog.alert("Please, give a correct name to your new column. The name will start with a letter or underscore, and only may contain alphanumeric characters and underscores", function() {
                  col_name.css('color','red').focus();
               });
               error=true;
               return false;
            }
         }
      }
   });

   if(!error){
      query[query.length-1]=query[query.length-1].split(',')[0];
      query.push(')');
      $('#query').attr('value',query.join(''));
      $('#database').attr('value',database);
      $('#form').submit();
   }

   //alert(query.join(''));
}